'''
Created on 2012-6-26

@author: wb_suoyao.shen
'''
from django.db import models,connection
from ssyblog.photos.PhotoAlbum import PhotoAlbum

class AlbumManager(models.Manager):
    def queryAlbumPreview(self):
        sql = ''' SELECT pa.id,pa.name,pa.description,v_pp.thumbnail FROM photos_album pa 
                    LEFT JOIN (SELECT pp.album,pp.thumbnail FROM photos_photos pp ORDER BY create_time DESC) v_pp 
                      ON pa.id = v_pp.album 
                   GROUP BY pa.id '''
        album_row = self.querySetRow(sql, None)
        album_preview_list = []
        for row in album_row:
            album_preview = PhotoAlbum(row[0],row[1],row[2],row[3])
            album_preview_list.append(album_preview)
        return album_preview_list

    def querySetRow(self,sql,param):
        cursor = connection.cursor()
        if param:
            cursor.execute(sql,param)
        else:
            cursor.execute(sql)
        row = cursor.fetchall()
        cursor.close()
        return row
    
class PhotosManager(models.Manager):
    def queryPhotosByPage(self,album=0,page=0):
        sql = ''' SELECT pp.id, pp.album, pp.image, pp.thumbnail, pp.caption 
                    FROM photos_photos pp 
                   WHERE pp.album = %s ORDER BY pp.create_time DESC LIMIT %s, %s 
              '''
        photos_list = self.raw(sql, [album,page,10])
        return photos_list

class Album(models.Model):
    name = models.CharField(max_length=250)
    description = models.CharField(max_length=256)
    create_time = models.DateTimeField(null=True,blank=True)
    modify_time = models.DateTimeField(null=True,blank=True)
    objects = AlbumManager()
    
    class Meta:
        ordering = ['name']
        
    def __unicode__(self):
        return self.name
    
    @models.permalink
    def get_absolute_url(self):
        return ('album_detail',None,{'object_id' : self.id})
    
class Photos(models.Model):
    album = models.IntegerField(max_length=11)
    image = models.CharField(max_length=5120,null=True,blank=True)
    thumbnail = models.CharField(max_length=5120,null=True,blank=True)
    caption = models.CharField(max_length=256,null=True, blank=True)
    create_time = models.DateTimeField(null=True,blank=True)
    objects = PhotosManager()
    
    class Meta:
        ordering=['-create_time']
        
    def __unicode__(self):
        return self.title
    
    @models.permalink
    def get_absolute_url(self):
        return ('photo_detail', None, {'object_id' : self.id})
